package com.ubb.smartsearch.searchengineif.faroo;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;

import javax.ejb.Stateless;

import com.ubb.smartsearch.searchengineif.AccessLocal;
import com.ubb.smartsearch.searchengineif.entity.Search;
import com.ubb.smartsearch.searchengineif.enums.FarooSearchParameter;
import com.ubb.smartsearch.searchengineif.exception.FieldParsingException;

@Stateless
public class FarooAccess implements AccessLocal {

	public String buildURLFromSearchEntity(Search search)
			throws FieldParsingException, UnsupportedEncodingException {

		StringBuilder url = new StringBuilder("http://www.faroo.com/api?");

		Field[] fields = search.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; ++i) {

			String fieldName = fields[i].getName();
			String fieldValue = getStringValueOfField(fieldName, search);

			if (fieldValue != null) {
				url.append(fieldName).append("=").append(fieldValue)
						.append("&");
			}
		}

		return url.deleteCharAt(url.length() - 1).toString();
	}

	private String getStringValueOfField(String fieldName, Search search)
			throws FieldParsingException, UnsupportedEncodingException {

		FarooSearchParameter sp = FarooSearchParameter.valueOf(fieldName);
		switch (sp) {
		case q:
			return URLEncoder.encode(search.getQ(), "UTF-8");
		case start:
			if (1 < search.getStart())
				return String.valueOf(search.getStart());
			else
				return null;
		case length:
			if (10 != search.getLength() && 0 != search.getLength())
				return String.valueOf(search.getLength());
			else
				return null;
		case rlength:
			if (20 != search.getRlength() && 0 != search.getRlength())
				return String.valueOf(search.getRlength());
			else
				return null;
		case l:
			if (search.getL() != null || !"en".equals(search.getL()))
				return search.getL();
			else
				return null;
		case src:
			if (!"web".equals(search.getSrc()))
				return search.getSrc();
			else
				return null;
		case kwic:
			// if (!search.getKwic())
			// return "false";
			// else
			return null;
		case i:
			if (search.getI())
				return "true";
			else
				return null;
		case f:
			if (!"json".equals(search.getF()))
				return search.getF();
			else
				return null;
		case jsoncallback:
			return search.getJsoncallback();
		}
		throw new FieldParsingException(fieldName);
	}
}
